﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Data.MultiTenancy/TenantProvider 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       TenantProvider
* 创建时间：  2025/5/26 10:59:12
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Data.MultiTenancy
{
     
    public class TenantProvider : ITenantProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _config;

        public TenantProvider(IHttpContextAccessor httpContextAccessor, IConfiguration config)
        {
            _httpContextAccessor = httpContextAccessor;
            _config = config;
        }

        public bool IsMultiTenantEnabled => _config.GetValue<bool>("MultiTenancy:Enabled");

        public Tenant? GetCurrentTenant()
        {
            if (!IsMultiTenantEnabled) return null;

            var tenantId = _httpContextAccessor.HttpContext?.Request.Headers["TenantId"].FirstOrDefault().ToLong();
            return _config.GetSection("Tenants").Get<List<Tenant>>()
                ?.FirstOrDefault(t => t.TenantId == tenantId);
        }
    }
}
